#!/usr/bin/env node
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";

const rl = readline.createInterface({ input, output });

// 获取命令行参数
const args = process.argv.slice(2);
const projectName = args[0];

if (!projectName) {
  console.error("请提供项目名称，例如：npx create-vue3-app my-project");
  process.exit(1);
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const templateDir = path.resolve(__dirname, "../packages/vue3-template");
const targetDir = path.resolve(projectName);

async function confirmOverwrite(dir: string): Promise<boolean> {
  if (await isDirectoryExist(dir)) {
    const answer = await rl.question(`${dir} 已存在，是否覆盖？(y/N): `);
    return answer.trim().toLowerCase() === "y";
  }
  return true;
}

async function isDirectoryExist(path: string): Promise<boolean> {
  try {
    const stats = await fs.stat(path);
    return stats.isDirectory();
  } catch (err) {
    return false;
  }
}

async function copyTemplateFiles(
  src: string,
  dest: string,
  projectName: string
) {
  const entries = await fs.readdir(src, { withFileTypes: true });

  for (const entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(
      dest,
      entry.name.replace(/__APP_NAME__/g, projectName)
    );

    if (entry.isDirectory()) {
      await fs.mkdir(destPath, { recursive: true });
      await copyTemplateFiles(srcPath, destPath, projectName);
    } else {
      const content = await fs.readFile(srcPath, "utf-8");
      const newContent = content.replace(/__APP_NAME__/g, projectName);
      await fs.writeFile(destPath, newContent);
    }
  }
}

async function createProject() {
  try {
    const shouldOverwrite = await confirmOverwrite(targetDir);
    if (!shouldOverwrite) {
      console.log("操作已取消。");
      return;
    }

    await fs.rm(targetDir, { recursive: true, force: true });
    await fs.mkdir(targetDir, { recursive: true });

    await copyTemplateFiles(templateDir, targetDir, projectName);

    console.log(`\n✅ 项目 ${projectName} 创建成功！`);
    console.log("进入项目目录并运行:");
    console.log(`  cd ${projectName}`);
    console.log(`  pnpm i`);
    console.log(`  pnpm dev`);
  } catch (error: any) {
    console.error(`❌ 创建项目失败: ${error.message}`);
    process.exit(1);
  } finally {
    rl.close();
  }
}

createProject();
